package com.woniuxy.service.impl;

import com.aliyun.oss.OSSClient;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author Leimin
 * @date 2022/05/10 09:22
 **/
@Service
public class OssServiceImpl implements OssService {
    @Value("${aliyun.oss.maxSize}")
    private int maxSize;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.dir.prefix}")
    private String dirPrefix;
    @Autowired
    private OSSClient ossClient;

    @Override
    public ResponseEntity upload(MultipartFile file) {
        try {
            return upload(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            return new ResponseEntity(500,"失败",e.getMessage());
        }
    }

    private ResponseEntity upload(InputStream inputStream, String name) {
        String objectName = getBucketName(name);
        // 创建PutObject请求。
        ossClient.putObject(bucketName, objectName, inputStream);

        return new ResponseEntity(200,"成功",formatPath(objectName));
    }

    //创建存放文件名
    private String getBucketName(String name){
        String ext = name.substring(name.lastIndexOf("."));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        String uuid = UUID.randomUUID().toString().replace("-","").substring(22);
        return dirPrefix+ date+"/"+ uuid+ext;
    }

    //拼接访问链接
    private String formatPath(String objectName){
        return "https://"  +bucketName+"."+ ossClient.getEndpoint().getHost() + "/" + objectName;
    }
}

